package com.jhy.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhy.common.utils.PageUtils;
import com.jhy.common.utils.Query;

import com.jhy.gulimall.product.dao.CategoryDao;
import com.jhy.gulimall.product.entity.CategoryEntity;
import com.jhy.gulimall.product.service.CategoryService;




@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //设置分类的子分类
        return entities.stream()
                //找到一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                //设置子分类
                .peek(menu -> menu.setChildren(getChildrens(menu, entities)))
                //排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                //收集
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查询所有子分类
     * @param root 当前分类
     * @param all 所有分类
     * @return 子分类集合
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                //过滤，如果root的id与all中数据的ParentCid相等，则为root的子分类
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                //递归，再次获取分类的子分类
                .peek(menu -> menu.setChildren(getChildrens(menu, all)))
                //排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                //收集
                .collect(Collectors.toList());
    }


}